package com.u17;


/**
 * @author u17
 * https://leetcode-cn.com/problems/merge-two-sorted-lists/
 */
public class Solution {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {}

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }


    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        //当作整个链表的头节点
        ListNode head = new ListNode(-1);
        //result不能为空，否则会报空指针异常,result就相当于一个指针
        ListNode result = head;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                result.next = l1;
                l1 = l1.next;
            } else {
                result.next = l2;
                l2 = l2.next;
            }
            //将当前result定位到该链表的最后一个节点
            result = result.next;
        }
        // 连接上剩下的节点
        result.next = l1 == null ? l2 : l1;
        return head.next;
    }
}
